package com.nowcoder.community.config;

import com.nowcoder.community.quartz.AlphaJob;
import com.nowcoder.community.quartz.PostScoreRefreshJob;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

//配置-》数据库-》调用
//Quartz 定时任务配置类
@Configuration
public class QuartzConfig {
    //FactoryBean可简化Bean的实例化过程：
    //1.通过FactoryBean封装Bean的实例化过程
    //2.将FactoryBean封装到Spring容器中
    //3.将FactoryBean注入给其他的Bean
    //4.该Bean得到的是FactoryBean所管理的对象实例

    // 配置JobDetail
    // @Bean
    public JobDetailFactoryBean alphaJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(AlphaJob.class);
        factoryBean.setName("alphaJob");
        factoryBean.setGroup("alphaJobGroup");//设置分组
        factoryBean.setDurability(true);//是否持久(数据库中是否删除)
        factoryBean.setRequestsRecovery(true);//是否可恢复
        return factoryBean;
    }

    // 配置Trigger(SimpleTriggerFactoryBean(简单任务用),CronTriggerFactoryBean(复杂任务用))
    // @Bean
    public SimpleTriggerFactoryBean alphaTrigger(JobDetail alphaJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(alphaJobDetail);
        factoryBean.setName("alphaTrigger");
        factoryBean.setGroup("alphaTriggerGroup");
        factoryBean.setRepeatInterval(3000);//执行频率
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }

    // 配置JobDetail
    // 刷新帖子分数的定时任务
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(PostScoreRefreshJob.class);
        factoryBean.setName("postScoreRefreshJob");
        factoryBean.setGroup("communityJobGroup");//设置分组
        factoryBean.setDurability(true);//是否持久(数据库中是否删除)
        factoryBean.setRequestsRecovery(true);//是否可恢复
        return factoryBean;
    }

    // 配置Trigger(SimpleTriggerFactoryBean(简单任务用),CronTriggerFactoryBean(复杂任务用))
    @Bean
    //postScoreRefreshJobDetail<-这个名字必须跟上面对应
    public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(postScoreRefreshJobDetail);
        factoryBean.setName("postScoreRefresh");
        factoryBean.setGroup("communityTriggerGroup");
        factoryBean.setRepeatInterval(1000 * 10);//执行频率
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }
}
